|
|
|
|
|
|
|
use the DISTINCTROW keyword. The following SQL statement (see Figure 8.22) uses DISTINCTROW to return the same records as the SQL statement in the previous example. |
|
|
|
|
|
|
|
|
SELECT DISTINCTROW *
FROM BookSales
ORDER BY Title |
|
|
|
|
|
|
|
|
Figure 8.22.
Using DISTINCTROW in an SQL statement. |
|
|
|
|
|
|
|
|
Both the DISTINCT and DISTINCTROW keywords enable you to limit the contents of the result set based on the uniqueness of one or more columns in the data table. In the next section, you'll learn how you can limit the contents of the result set to the records with the highest numeric values in selected columns. |
|
|
|
|
|
|
|
|
The TOP n and TOP n PERCENT Clauses |
|
|
|
|
|
|
|
|
You can use the TOP n or TOP n PERCENT SQL keywords to limit the number of records in your result set. Suppose you want to get a list of the five top-selling books in a data table. You can use the TOP n clause to get just that. TOP n returns the first n number of records. If you have two records of the same value, SQL returns both records. For the previous example, if the fifth and sixth records were both equal, the result set would contain six records, not just five. |
|
|
|
|
|
|
|
|
When you use the TOP clause, you must also use the ORDER BY clause to make sure that your result set is sorted. If you do not use the ORDER BY clause, you receive an arbitrary set of records because SQL first executes the ORDER BY clause and then selects the TOP n records you requested. Without the ORDER BY clause, it is quite likely that you will not get the results you intended. If a WHERE clause is present, SQL performs the WHERE clause, the ORDER BY clause, and then the TOP n clause. As you can see, failure to use the ORDER BY clause most certainly returns garbage in your result set (see Figure 8.23). |
|
|
|
|
|
|
|
|
SELECT TOP 5 * FROM BookSales
ORDER BY Sales DESC |
|
|
|
|
|